package com.levy.contronller.javaWeb.threadMasterWorker;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

public class Master {

    //1.装任务的集合
    private ConcurrentLinkedQueue<Task> wokerQueue = new ConcurrentLinkedQueue<>();

    //2.装所有worker对象
    private HashMap<String, Thread> workers = new HashMap<>();

    //3.每一个worker并行执行后的结果集
    private ConcurrentHashMap<String, Object> resultMap = new ConcurrentHashMap<>();

    //4.构造方法
    public Master(Worker worker, int count) {


        //每个worker对象都需要有master的引用 workerqueue用于领取任务 resultMap用于任务的提交
        worker.setWorkerQueue(this.wokerQueue);
        worker.setResultMap(resultMap);

        for (int i = 0; i < count; i++) {
            workers.put("node" + i, new Thread(worker));
        }
    }

    //5.提交方法
    public void submit(Task task) {
        this.wokerQueue.add(task);
    }

    //6.执行方法
    public void execute() {
        for (Map.Entry<String, Thread> me : workers.entrySet()) {
            me.getValue().start();
        }
    }


    //判断线程是否执行完毕
    public boolean isComplete() {
        for (Map.Entry<String, Thread> me : workers.entrySet()) {
            if (me.getValue().getState() != Thread.State.TERMINATED) {
                return false;
            }
        }
        return true;
    }

    public Long gerResult() {
        long ret = 0L;
        for (Map.Entry<String, Object> me : resultMap.entrySet()) {
            //汇总
            ret += (Integer)me.getValue();
        }
        return ret;

    }
}
